package com.oriole.admin.utils;

import com.oriole.common.constant.ResultModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/9/13 20:03
 * description:
 */
public class PageableUtil {

    public static Pageable getPageable(OriolePage page) {
        if (StringUtils.isBlank(page.getSortParam())) {
            return PageRequest.of(page.getCurrentPage() - 1, page.getPageSize());
        }
        Sort.Direction direction = Sort.Direction.ASC;
        if (!direction.toString().equalsIgnoreCase(page.getSort())) {
            direction = Sort.Direction.DESC;
        }
        return PageRequest.of(page.getCurrentPage(), page.getPageSize(), Sort.by(direction, page.getSortParam()));
    }

    public static OrioleResultPage<Object> setResultPage(ResultModel<Object> resultModel) {
        String data = JacksonUtil.pojo2Json(resultModel.getData());
        Map<String, Object> map = JacksonUtil.json2Map(data);
        OrioleResultPage<Object> resultPage = new OrioleResultPage<>();
        resultPage.setCurrentPage(Integer.parseInt(map.get("number").toString()) + 1);
        resultPage.setPageSize(Integer.parseInt(map.get("size").toString()));
        resultPage.setTotal(Integer.parseInt(map.get("totalElements").toString()));
        resultPage.setContent(map.get("content"));
        return resultPage;
    }

}
